import json

import requests

import common.textIn as textIn


def get_file_content(file_path):
    with open(file_path, 'rb') as fp:
        return fp.read()


class TextIn:
    def __init__(self, img_path):
        self._app_id = textIn.access_key
        self._secret_code = textIn.secret_key
        self._img_path = img_path

    def recognize(self):
        url = textIn.Image_recognize_table_url
        headers = {
            'x-ti-app-id': self._app_id,
            'x-ti-secret-code': self._secret_code
        }
        try:
            image = get_file_content(self._img_path)
            response = requests.post(url, data=image, headers=headers)
            if response.status_code == 200:
                result_json = response.json()
                with open('result.json', 'w', encoding='utf-8') as f:
                    json.dump(result_json, f, ensure_ascii=False, indent=4)
                return result_json
            else:
                return {"error": "请求失败，状态码：" + str(response.status_code)}
        except Exception as e:
            return {"error": "发生异常：" + str(e)}


def extract_table_data_v2(filepath: str):
    text_in = TextIn(filepath)
    result = text_in.recognize()
    return result


# 示例用法
filepath = "example.jpg"
result = extract_table_data_v2(filepath)
print(result)
